<?php
class UsersController extends AppController {
    var $name = 'Users';
        
    function beforeFilter() {
        $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'homepage_redirect');
        $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'homepage_redirect');
    }
    
    function add() {
        $this->pageTitle = "添加新用户";
        if ($this->Auth->user('role') == 'admin'){
            if ($this->data) {
                if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])) {
                    $this->User->create();
                    $this->User->save($this->data);
                    if ($this->data['User']['role'] == 'student') {
                        $this->User->StudentProfile->save(array('user_id' => $this->User->id));
                        $this->redirect(array('controller' => 'student_profiles', 'action' => 'edit', $this->User->StudentProfile->id));
                    }
                    else if ($this->data['User']['role'] == 'teacher') {
                        $this->User->TeacherProfile->save(array('user_id' => $this->User->id));
                        $this->redirect(array('controller' => 'teacher_profiles', 'action' => 'edit', $this->User->TeacherProfile->id));
                    }
                    else {
                        $this->redirect(array('action' => 'login'));
                    }
                }
                else {
                    $this->Session->setFlash("密码不匹配");
                }
            }
        }
        else {
            $this->Session->setFlash("您没有相应的权限");
            $this->redirect(array('action' => 'login'));
        }
    }
    
    function login() {
        $this->pageTitle = "登录系统";
    }
    
    function logout() {
        $this->Session->setFlash("您已经退出系统");
        $this->redirect($this->Auth->logout());
    }
    
    function homepage_redirect() {
        if ($this->Auth->user('role') == 'student') {
            $this->redirect(array('controller' => 'student_profiles', 'action' => 'index'));
        }
        else if ($this->Auth->user('role') == 'teacher') {
            $this->redirect(array('controller' => 'teacher_profiles', 'action' => 'index'));
        }
        else if ($this->Auth->user('role') == 'admin') {
            $this->redirect(array('controller' => 'users', 'action' => 'manage'));
        }
    }
    
    function manage() {
        if ($this->Auth->user('role') == 'admin') {
        }
        else {
            $this->Session->setFlash("您没有相应的权限");
            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }
}
?>
